package org.yun.util;

import com.alibaba.fastjson.JSON;
import org.yun.biz.model.RedPack;
import org.yun.exception.BizException;
import org.yun.exception.ErrorCode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.yun.constants.Constant.MIN_RED_PACK;
import static org.yun.constants.RedisConstant.*;

/**
 * @author liyunfeng31
 */
public class CommonUtil {

    /**
     * 参数校验
     * @param redPack redPack
     */
    public static void checkRedPackParam(RedPack redPack){
        if(redPack.getNum()<1){
            throw new BizException(ErrorCode.RED_PACK.NUM_TOO_FEW);
        }
        double re = redPack.getAmount().doubleValue() / redPack.getNum();
        if(re < MIN_RED_PACK){
            throw new BizException(ErrorCode.RED_PACK.AMOUNT_TOO_FEW);
        }
    }


    /**
     * 红包Model转map
     * @param redPack redPack
     * @return map
     */
    public static Map<String, String> redToMap(RedPack redPack){
        Map<String, String> map = new HashMap<>(7);
        map.put("redPackId",redPack.getRedPackId().toString());
        map.put("title",redPack.getTitle());
        map.put("amount",redPack.getAmount().toString());
        map.put("num", redPack.getNum().toString());
        map.put("remainingAmount",redPack.getAmount().toString());
        map.put("remainingNum",redPack.getNum().toString());
        map.put("groupId",redPack.getGroupId().toString());
        return map;
    }



    /**
     * 拼装key
     * @param redPackId 红包ID
     * @return keys
     */
    public static List<String> keys(Long redPackId){
        String redKey = RED_PACK + redPackId;
        String usersKey = RED_PACK + redPackId + RP_USER;
        String recordKey = RED_PACK + redPackId + RP_RECORD;
        return Arrays.asList(redKey,usersKey,recordKey);
    }


    /**
     * 脚本参数
     * @param redPackId  红包ID
     * @param rAmount 剩余金额
     * @param rNum 剩余个数
     * @return 参数
     */
    public static String param(Long redPackId, int rAmount, int rNum, int grabAmount){
        Map<String, Object> map = new HashMap<>(3);
        map.put("redPackId",redPackId);
        map.put("remainingAmount",rAmount);
        map.put("remainingNum",rNum);
        map.put("grabAmount",grabAmount);
        return JSON.toJSONString(map);
    }

}
